package com.reebake.ideal.security.service.controller;

import cn.hutool.core.util.IdUtil;
import com.reebake.ideal.holder.UserContextHolder;
import com.reebake.ideal.message.client.MessageClient;
import com.reebake.ideal.message.core.MessageMediumTypeConstants;
import com.reebake.ideal.message.core.MessageTypeConstants;
import com.reebake.ideal.message.entity.MessageSendDTO;
import com.reebake.ideal.security.service.entity.QrcodeAuthVO;
import com.reebake.ideal.verify.code.core.VerifyCodeStorage;
import com.reebake.ideal.verify.code.entity.VerifyCodeEntity;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
@RestController
@RequestMapping("/user/auth/qrcode")
public class QrcodeAuthController {

    private final MessageClient messageClient;
    private final VerifyCodeStorage verifyCodeStorage;

    @PostMapping("create")
    public QrcodeAuthVO create() {
        String sessionId = IdUtil.fastSimpleUUID();

        QrcodeAuthVO qrcodeAuthVO = new QrcodeAuthVO();
        qrcodeAuthVO.setSessionId(sessionId);

        return qrcodeAuthVO;
    }

	@PostMapping("scan")
	public void scan(@Valid @RequestBody QrcodeAuthVO qrcodeVO) {
        String sessionId = qrcodeVO.getSessionId();
		// notify web application user
    	MessageSendDTO messageSendDTO = new MessageSendDTO();
        messageSendDTO.setChannelId(null);
        messageSendDTO.setReceiverIds(sessionId);
        messageSendDTO.setMediumType(MessageMediumTypeConstants.APP);
        messageSendDTO.setMessageType(MessageTypeConstants.CMD);
        messageSendDTO.setTitle("scanned");
        
        messageClient.send(messageSendDTO);
	}
	
	@PostMapping("confirm")
	public void confirm(@Valid @RequestBody QrcodeAuthVO qrcodeVO) {
        String sessionId = qrcodeVO.getSessionId();
		String userId = UserContextHolder.getCurrentUserId();
		String verifyCode = IdUtil.fastSimpleUUID();

		// notify application login
		MessageSendDTO messageSendDTO = new MessageSendDTO();
        messageSendDTO.setChannelId(null);
        messageSendDTO.setReceiverIds(qrcodeVO.getSessionId());
        messageSendDTO.setMediumType(MessageMediumTypeConstants.APP);
        messageSendDTO.setMessageType(MessageTypeConstants.CMD);
        messageSendDTO.setContent(verifyCode);
        messageSendDTO.setTitle("login");

        VerifyCodeEntity verifyCodeEntity = new VerifyCodeEntity();
        verifyCodeEntity.setReceiver(sessionId);
        verifyCodeEntity.setVerifyCode(verifyCode);
        verifyCodeEntity.setExtParam(userId);

        messageClient.send(messageSendDTO);
        verifyCodeStorage.save(verifyCodeEntity);
	}
	
}
